import random

from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from django_redis import get_redis_connection
import logging
# from meiduo_mall.meiduo_mall.apps.verifications.serializers import ImageCodeCheckSerializer
# from meiduo_mall.meiduo_mall.libs.captcha.captcha import captcha
# from meiduo_mall.libs.captcha import captcha
# from meiduo_mall.meiduo_mall.utils.yuntongxun.sms import CCP
from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.utils.yuntongxun.sms import CCP
from verifications.serializers import ImageCodeCheckSerializer
from . import constants
# from meiduo_mall import meiduo_mall
# Create your views here.
from celery_tasks.sms.tasks import send_sms_code
logger = logging.getLogger('django')

class ImageCodeView(APIView):

    '''图片验证码'''
    def get(self, request, image_code_id):

        #生成验证码图片
        text, image = captcha.generate_captcha()
        #保存真实值
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        #返回图片
        # return HttpResponse(image, content_type='image/jpg')
        return HttpResponse(image, content_type='image/jpg')

class SMSCodeView(GenericAPIView):
# class SMSCodeView(GenericAPIView):

    '''
    短信验证码
    传入参数
        mobile，image_code_id,  text

    '''
    serializer_class = ImageCodeCheckSerializer
    def get(self, requeset, mobile, SMS_CODE_TEMP_ID=None):
        #校验参数    由序列化器完成
        serializer = self.get_serializer(data = requeset.query_params)
        serializer.is_valid(raise_exception=True)
        #生成短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        #保存短信验证码  发送记录
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        #让管道通知redis执行命令
        pl.execute()

        # #发送短信
        # try:
        #     ccp = CCP()
        #     sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        #
        #     result = ccp.send_template_sms(mobile, [sms_code, ], constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送验证码短信[异常] [ mobile: %s, message: %s ]" % (mobile, e))
        #     return Response({'message' : 'failed'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # else:
        #     if result == 0:
        #         logger.info("发送验证码短信【正常】[ mobile: %s ] " % mobile)
        #         return Response({'message': 'ok'})
        #     else:
        #         logger.warning("发送验证码短信【失败】[ mobile: %s]" % mobile)
        #         return Response({'message' : 'failed'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        #

        #使用celery发送短信验证码
        expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)

        send_sms_code.delay(mobile, sms_code, expires, constants.SMS_CODE_TEMP_ID)